﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using Chire.ChireInter.Students;
using Chire.ChireInter.Teacher;
using Chire.ChireInter.Wechat;
using Newtonsoft.Json;

namespace Chire.ChireInter.Identity
{
    /// <summary>
    /// Identity_Auth_Notice 的摘要说明
    /// </summary>
    public class Identity_Auth_Notice : IHttpHandler
    {
        HttpContext contextWithBase;
        string auth_type = "";                  // 认证类型
        string code = "";                       // 传入code
        string openid = "";                     // openid
        string auth_key = "";                   // 认证的人的id
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            contextWithBase = context;
            analysisInfo();
        }

        #region 验证参数
        public void analysisInfo()
        {
            if (contextWithBase.Request.Form.AllKeys.Contains("auth_type"))
            {
                auth_type = contextWithBase.Request.Form["auth_type"];
            }
            if (contextWithBase.Request.Form.AllKeys.Contains("code"))
            {
                code = contextWithBase.Request.Form["code"];
            }
            if (contextWithBase.Request.Form.AllKeys.Contains("auth_key"))
            {
                auth_key = contextWithBase.Request.Form["auth_key"];
            }
            if (contextWithBase.Request.Form.AllKeys.Contains("openid"))
            {
                openid = contextWithBase.Request.Form["openid"];
            }
            noticeManager();
        }
        #endregion

        #region 进行通知
        public void noticeManager() { 
            // 1.获取当前的推送次数
            Identity_Action identityAction = new Identity_Action();
            int times = identityAction.bindingNotice(code, auth_key,openid);
            if (times < 3)          //success
            {
                // 1. 进行发送认证信息
                noticeSubManager();
            }
            else
            {
                successManager("-1", "您的绑定次数已经超过3次。系统已判定为非法操作，请联系管理员");
            }

        }

        public void noticeSubManager() { 
            // 0. 根据code 获取openid
            Wechat_Action wechatAction = new Wechat_Action();
            string openId = "";
            if (openid.Length > 0)
            {
                openId = openid;
            }
            else {
                openId = wechatAction.getOpenIdWithCode(code);
            }
                      

            // 1.获取随机验证码
            Identity_Action identityAction = new Identity_Action();
             string randomCode = identityAction.noticeManagerHasCode(openId, auth_type);
             if (randomCode.Length == 0)
             {
                 randomCode = addSmsCode();
                 identityAction.insertRandomCode(openId, auth_type, randomCode);
                 // 3.插入计数
                 identityAction.bindingNoticeTimesInsert(openId, auth_key);
             }
             else {
                 // 3. 发送计数+1
                 identityAction.bindingNoticeTimesUpdate(openId, auth_key);
             }
            // 2. 进行发送
            if (auth_type.Equals("1")){         // 家长绑定学生
                // 1. 获取学生信息
                Student_Action studentAction = new Student_Action();
                Student_Model studentModel = studentAction.getStudentInfoWithId(auth_key);
                // 2. 进行发送信息
                identityAction.adminNoticeManager(randomCode, auth_type, studentModel.id, studentModel.name);
            
                successManager("200", openId + auth_key);
            }
            else if (auth_type.Equals("2")) {   // 老师绑定管理员
                Teacher_Action teacherAction = new Teacher_Action();
                List<Teacher_Model> adminList = teacherAction.getAllAdminManager();
                for (int i = 0; i < adminList.Count; i++)
                {
                    Teacher_Model teacherModel = adminList[i];
                    identityAction.adminNoticeManager(randomCode, auth_type, openId, teacherModel.name);  
                }
     
                successManager("200", "success");
            }
        }
        #endregion

        #region 3.生成验证码
        private string addSmsCode()
        {
            Random Rdm = new Random();
            //产生0到100的随机数
            int iRdm = Rdm.Next(0, 10000);

            return iRdm.ToString();
        }
        #endregion
      

        #region 其他方法
        public void successManager(string code,string err) {
            OUTIdentity_BindingTimes_Model out_base_setting = new OUTIdentity_BindingTimes_Model();
            out_base_setting.errCode = code;
            out_base_setting.errMsg = err;
         

            JsonSerializer serializer = new JsonSerializer();
            StringWriter sw = new StringWriter();
            serializer.Serialize(new JsonTextWriter(sw), out_base_setting);
            string info = sw.GetStringBuilder().ToString();
            contextWithBase.Response.Write(sw.GetStringBuilder().ToString());
        }
        #endregion

        #region 其他
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        #endregion
       
    }
}